<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Java 后端 Websocket的tomcat实现</title>
    <script src="https://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
</head>
<body>
<input type="hidden" id="sid" th:value="${sid}">
<input id="msg_input" type="text"/>
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭WS连接</button>
<hr/>
<div id="message_body"></div>
</body>
<script type="text/javascript">
    var websocket = null;
    var sid = document.getElementById('sid').value;
    console.log('sid:' + sid)
    // 检查浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:8080/api/ws/' + sid)
        // 连接发生错误回调
        websocket.onerror = () => {
            setMessageInnerHTML('WebSocket连接发生错误');
        }

        // 连接成功回调
        websocket.onopen = () => {
            setMessageInnerHTML('WebSocket连接成功')
        }

        // 接收消息回调
        websocket.onmessage = (event) => {
            console.log(event)
            setMessageInnerHTML('[服务器]' + event.data)
        }

        // 连接关闭回调
        websocket.onclose = () => {
            setMessageInnerHTML('WebSocket连接关闭')
        }

        // 监听窗口关闭事件
        window.onbeforeunload = function () {
            closeWebSocket()
        }

        // 将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message_body').innerHTML += innerHTML + '<br/>'
        }

        // 关闭WebSocket连接
        function closeWebSocket() {
            websocket.close()
        }

        // 发送消息
        function send() {
            var message = document.getElementById('msg_input').value
            websocket.send('{"msg":"' + message + '"}')
            setMessageInnerHTML(message + "&#13;")
        }

    } else {
        alert('当前浏览器不支持websocket')
    }

    // 获取url后面的参数
    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

</script>
</html>